package com.dlc.shop.user.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.param.UserUpdateParam;
import com.dlc.shop.common.annotation.SysLog;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.security.common.util.AuthUserContext;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.user.common.dto.UserTagDto;
import com.dlc.shop.user.common.model.UserTag;
import com.dlc.shop.user.common.model.UserTagUser;
import com.dlc.shop.user.common.service.UserTagService;
import com.dlc.shop.user.common.service.UserTagUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 客户标签
 *
 * @author LGH
 * @date 2020-09-09 11:31:16
 */
@Tag(name = "客户标签")
@RestController
@AllArgsConstructor
@RequestMapping("/user/userTag")
public class UserTagController {

    private final UserTagService userTagService;
    private final UserTagUserService userTagUserService;

    @GetMapping("/info/{userTagId}")
    @Operation(summary = "查询(会员/客户)标签信息", description =  "通过id查询(会员/客户)标签")
    @PreAuthorize("@pms.hasPermission('user:userTag:info')")
    public ServerResponseEntity<UserTag> getById(@PathVariable("userTagId") Long userTagId) {
        return ServerResponseEntity.success(userTagService.getById(userTagId));
    }

    @PostMapping
    @Operation(summary = "新增(会员/客户)标签", description =  "新增(会员/客户)标签")
    @PreAuthorize("@pms.hasPermission('user:userTag:save')")
    public ServerResponseEntity<String> save(@RequestBody @Validated(UserTagDto.AddUserTag.class) UserTagDto userTagDto) {
        Long shopId = AuthUserContext.getShopId();
        userTagDto.setShopId(shopId);
        // 自动标签数量上限校验
        if(Objects.equals(userTagDto.getTagType(),1)) {
            long count = userTagService.count(new LambdaQueryWrapper<UserTag>()
                    .eq(UserTag::getTagType, 1)
                    .eq(UserTag::getTagCategory, userTagDto.getTagCategory())
                    .eq(UserTag::getShopId, userTagDto.getShopId()));
            if (count + 1 > Constant.TAG_LIMIT_NUM) {
                throw new YamiShopBindException("yami.tag.num.check");
            }
        }
        // 标签名重名校验
        long nameCount = userTagService.count(new LambdaQueryWrapper<UserTag>()
                .eq(UserTag::getTagName, userTagDto.getTagName())
                .eq(UserTag::getTagCategory, userTagDto.getTagCategory())
                .eq(UserTag::getShopId, userTagDto.getShopId()));
        if(nameCount > 0){
            throw new YamiShopBindException("yami.tag.name.exist");
        }
        return ServerResponseEntity.success(userTagService.addUserTag(userTagDto));
    }

    @PutMapping
    @Operation(summary = "修改(会员/客户)标签", description =  "修改(会员/客户)标签")
    @PreAuthorize("@pms.hasPermission('user:userTag:update')")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Validated(UserTagDto.UpdateUserTag.class) UserTagDto userTagDto) {
        Long shopId = AuthUserContext.getShopId();
        userTagDto.setShopId(shopId);
        // 标签名重名校验
        long nameCount = userTagService.count(new LambdaQueryWrapper<UserTag>()
                .eq(UserTag::getTagName, userTagDto.getTagName())
                .eq(UserTag::getShopId, userTagDto.getShopId())
                .ne(UserTag::getUserTagId, userTagDto.getUserTagId()));
        if(nameCount > 0){
            throw new YamiShopBindException("yami.tag.name.exist");
        }
        return ServerResponseEntity.success(userTagService.updateUserTag(userTagDto));
    }

    @SysLog("删除客户标签")
    @DeleteMapping("/{userTagId}")
    @Operation(summary = "删除(客户/会员)标签", description =  "删除(客户/会员)标签")
    @PreAuthorize("@pms.hasPermission('user:userTag:delete')")
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long userTagId) {
        return ServerResponseEntity.success(userTagService.removeUserTag(userTagId));
    }

    @SysLog("刷新客户标签统计数据")
    @GetMapping("/refresh/{userTagId}")
    @Operation(summary = "刷新指定客户标签统计数据", description =  "通过id刷新客户标签统计数据")
    @PreAuthorize("@pms.hasPermission('user:userTag:refresh')")
    public ServerResponseEntity<UserTag> refreshUserTag(@PathVariable("userTagId") Long userTagId) {
        UserTag userTag = userTagService.refreshShopConditionTag(userTagId);
        return ServerResponseEntity.success(userTag);
    }

    @PreAuthorize("@pms.hasPermission('user:userTag:refresh')")
    @Operation(summary = "批量刷新客户标签")
    @Parameter(name = "tagIds", description = "标签id集合（不传默认更新全部）")
    @GetMapping("/batchRefresh")
    public ServerResponseEntity<Void> refreshAllTag(@RequestParam(required = false) List<Long> tagIds) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (CollectionUtils.isEmpty(tagIds)) {
            // 查询所有条件标签
            List<UserTag> userTags = userTagService.list(new LambdaQueryWrapper<UserTag>()
                    .eq(UserTag::getShopId, shopId)
                    .eq(UserTag::getTagType, 1));
            if (CollectionUtils.isEmpty(userTags)) {
                return ServerResponseEntity.success();
            }
            tagIds = userTags.stream().map(UserTag::getUserTagId).collect(Collectors.toList());
        }
        userTagService.batchRefreshShopConditionTag(tagIds);
        return ServerResponseEntity.success();
    }

    @SysLog("查看客户标签")
    @GetMapping("/getTagList" )
    @Operation(summary = "查询（客户/会员）标签集合", description =  "查询（客户/会员）标签集合")
    @PreAuthorize("@pms.hasPermission('user:userTag:list')")
    public ServerResponseEntity<List<UserTag>> getTagList(Integer tagCategory) {
        Long shopId = AuthUserContext.getShopId();
        return ServerResponseEntity.success(userTagService.list(new LambdaQueryWrapper<UserTag>()
                .eq(UserTag::getTagCategory, tagCategory)
                .eq(UserTag::getShopId, shopId)));
    }

    @SysLog("给对应标签的用户推送消息" )
    @DeleteMapping("/sendMsg/{templateId}" )
    @Operation(summary = "给对应标签的用户推送消息", description =  "通过消息id推送给对应标签的用户")
    @PreAuthorize("@pms.hasPermission('platform:notifyTemplate:update')" )
    public ServerResponseEntity<Void> sendMsg(@PathVariable Long templateId) {
        userTagService.sendTagMsg(templateId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/byTagType")
    @Operation(summary = "分页获取标签", description =  "分页获取标签")
    @PreAuthorize("@pms.hasPermission('user:userTag:page')")
    public ServerResponseEntity<IPage<UserTag>> getTagPage(PageParam<UserTag> page, UserTag userTag) {
        Long shopId = AuthUserContext.getShopId();
        PageParam<UserTag> resPage = userTagService.page(page, new LambdaQueryWrapper<UserTag>()
                .eq(userTag.getTagType() != null,UserTag::getTagType, userTag.getTagType())
                .eq(userTag.getTagCategory() != null, UserTag::getTagCategory, userTag.getTagCategory())
                .like(StrUtil.isNotBlank(userTag.getTagName()), UserTag::getTagName, userTag.getTagName())
                .eq(UserTag::getShopId, shopId)
                .orderByDesc(UserTag::getCreateTime)
        );
        return ServerResponseEntity.success(resPage);
    }

    @PutMapping("/updateBatchTag")
    @Operation(summary = "批量打标签", description =  "批量打标签")
    @PreAuthorize("@pms.hasPermission('user:userTag:updateBatch')")
    public ServerResponseEntity<Void> updateBatchTag(@RequestBody UserUpdateParam userUpdateParam) {
        Long shopId = AuthUserContext.getShopId();
        userTagService.updateBatchTag(userUpdateParam, shopId);
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/deleteUserTag")
    @Operation(summary = "删除指定会员的指定标签", description =  "删除指定会员的指定标签")
    @PreAuthorize("@pms.hasPermission('user:userTag:deleteUserTag')")
    public ServerResponseEntity<Boolean> deleteUserTag(@RequestBody UserTagUser tagUser) {
        return ServerResponseEntity.success(userTagUserService.removeByUserIdAndTagId(tagUser.getUserId(),tagUser.getUserTagId()));
    }
}
